package com.xdja.uac;

/**
 * Author:kongguoguang
 * Date:2020/6/16
 * Time:14:09
 * Summary:
 */
public class LinkedListUtil {

    private static class Node {
        Node(String data){
            this.data = data;
        }

        String data;

        Node next;

    }

    /**
     * 反转链表
     * @param head 原始链表首部节点
     * @return 反转后的链表首部节点
     */
    public static Node invertLinkedList(Node head){
        if (head == null){
            return null;
        }

        //当前节点
        Node currentNode = head;

        //当前节点的上一个节点
        Node preNode = null;

        //当前节点的下一个节点
        Node nextNode;

        while (currentNode != null){
            nextNode = currentNode.next;
            currentNode.next = preNode;

            preNode = currentNode;
            currentNode = nextNode;
        }
        return preNode;
    }

    /**
     * 打印链表
     * @param head 链表首部节点
     */
    public static void printLinkList(Node head){
        while (head != null){
            System.out.println(head.data);
            head = head.next;
        }
    }

    public static void main(String[] args) {
        Node one = new Node("1");
        Node two = new Node("2");
        Node three = new Node("3");
        Node four = new Node("4");
        Node five = new Node("5");
        Node six = new Node("6");

        one.next = two;
        two.next = three;
        three.next = four;
        four.next = five;
        five.next = six;
        System.out.println("print original linked list");
        printLinkList(one);

        Node invertedHead = invertLinkedList(one);

        System.out.println("print inverted linked list");
        printLinkList(invertedHead);
    }
}
